const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');
const Koa = require('koa');
const cors = require('koa2-cors');
const koaBody = require('koa-bodyparser');
const app = new Koa();

// 环境配置
const ENV = process.env.NODE_ENV || 'development';
const JWT_SECRET = process.env.JWT_SECRET || 'your_secret_key';
const JWT_EXPIRES_IN = '1h';

// 内存缓存（初始化时加载文件数据）
let cache = {
    user: [],
    department: [],
    materials: [],
    vehicleManagement: [],
    jobManagement: [],
    finance: [],
    processApproval: [],
    meeting: []
};
let lastFileUpdate = 0;
const CACHE_TTL = 60 * 1000;

// 统一权限验证函数
const requireAuth = (ctx, next) => {
    return authMiddleware(ctx, next);
};

// 生成Token中间件
const generateToken = (user) => {
    return jwt.sign(
        { userId: user.id, username: user.username },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
    );
};

// Token验证中间件
const authMiddleware = async (ctx, next) => {
    const authHeader = ctx.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        ctx.status = 401;
        ctx.body = { error: '未提供认证令牌' };
        return;
    }

    const token = authHeader.split(' ')[1];
    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        ctx.state.user = decoded;
        await next();
    } catch (err) {
        ctx.status = 401;
        ctx.body = { error: '无效或过期的认证令牌' };
    }
};

// 读取文件并更新缓存（改进版）
const readFileAndUpdateCache = async () => {
    try {
        const filePath = path.join(__dirname, 'oa.json');
        if (!fs.existsSync(filePath)) {
            console.log('[文件读取] 文件不存在，使用默认缓存');
            return cache;
        }

        const data = await fs.promises.readFile(filePath, 'utf8');
        const jsonData = JSON.parse(data);

        // 安全合并文件数据到缓存（保留现有非空数据）
        cache.user = Array.isArray(jsonData.user) ? jsonData.user : cache.user;
        cache.department = Array.isArray(jsonData.department) ? jsonData.department : cache.department;
        cache.materials = Array.isArray(jsonData.materials) ? jsonData.materials : cache.materials;
        cache.vehicleManagement = Array.isArray(jsonData.vehicleManagement) ? jsonData.vehicleManagement : cache.vehicleManagement;
        cache.jobManagement = Array.isArray(jsonData.jobManagement) ? jsonData.jobManagement : cache.jobManagement;
        cache.finance = Array.isArray(jsonData.finance) ? jsonData.finance : [];
        cache.processApproval = Array.isArray(jsonData.processApproval) ? jsonData.processApproval : cache.processApproval;
        cache.meeting = Array.isArray(jsonData.meeting) ? jsonData.meeting : cache.meeting;

        lastFileUpdate = Date.now();
        console.log('[缓存更新] 数据已加载');
        return cache;
    } catch (error) {
        console.error('文件读取失败，使用现有缓存:', error);
        return cache;
    }
};

// 写入文件并更新缓存（改进版）
const writeFileAndUpdateCache = async (updatedData) => {
    const filePath = path.join(__dirname, 'oa.json');
    try {
        // 只更新指定的模块，保留其他模块数据
        Object.keys(updatedData).forEach(key => {
            if (cache[key] !== undefined) {
                cache[key] = updatedData[key];
            }
        });

        // 写入完整缓存到文件（确保所有模块都被保留）
        await fs.promises.writeFile(
            filePath,
            JSON.stringify(cache, null, 2)
        );
        lastFileUpdate = Date.now();
        console.log('[文件写入] 数据已持久化');
    } catch (error) {
        console.error('文件写入失败:', error);
        throw error;
    }
};

// 统一错误处理
const errorHandler = (ctx, error) => {
    console.error('服务器错误:', error);
    ctx.status = error.status || 500;
    ctx.body = {
        error: error.message || '服务器内部错误',
        stack: ENV === 'development' ? error.stack : undefined
    };
};

// 中间件配置
app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    headers: ['Content-Type', 'Authorization'],
    exposeHeaders: ['Authorization', 'X-Token']
}));

app.use(koaBody({
    json: true,
    text: false,
    form: false
}));

app.use(async (ctx, next) => {
    try {
        await next();
    } catch (error) {
        errorHandler(ctx, error);
    }
});

// 缓存中间件（优化版）
app.use(async (ctx, next) => {
    const now = Date.now();
    if (now - lastFileUpdate > CACHE_TTL) {
        await readFileAndUpdateCache();
    }
    ctx.state.cache = cache;
    await next();
});

app.use(async (ctx) => {
    // ====================== 部门接口 ======================
    if (ctx.path.startsWith('/department')) {
        const id = ctx.path.split('/')[2];
        const { head } = ctx.query;

        switch (ctx.method) {
            case 'GET':
                if (head) {
                    // 优化：使用缓存数据进行过滤
                    const filtered = cache.department.filter(dept =>
                        dept.DepartmentHead?.toLowerCase().includes(head.toLowerCase())
                    );
                    ctx.body = filtered;
                } else if (id) {
                    const department = cache.department.find(d => d.id === id);
                    ctx.body = department || { error: '部门不存在' };
                } else {
                    ctx.body = cache.department;
                }
                break;

            case 'POST':
                await authMiddleware(ctx, async () => { // 需要权限
                    const newDepartment = ctx.request.body;
                    if (!newDepartment.department) {
                        ctx.status = 400;
                        ctx.body = { error: '缺少部门名称' };
                        return;
                    }

                    const newIndex = cache.department.length + 1;
                    newDepartment.OrganizationCode = `ZT${newIndex.toString().padStart(4, '0')}`;
                    newDepartment.DepartmentHead = newDepartment.DepartmentHead || '';
                    newDepartment.typeOfOrganization = newDepartment.typeOfOrganization || '部门';
                    newDepartment.authorizedStaffCount = newDepartment.authorizedStaffCount || '0';
                    newDepartment.activeStaffCount = newDepartment.activeStaffCount || '0';
                    newDepartment.id = newIndex.toString();
                    newDepartment.action = [{ text: '编辑' }, { text: '删除' }];

                    cache.department.push(newDepartment);
                    await writeFileAndUpdateCache({
                        ...ctx.state.jsonData,
                        department: cache.department
                    });

                    ctx.status = 201;
                    ctx.body = { message: '部门添加成功', data: newDepartment };
                });
                break;

            case 'PUT':
                await authMiddleware(ctx, async () => { // 需要权限
                    if (!id) {
                        ctx.status = 400;
                        ctx.body = { error: '缺少部门ID' };
                        return;
                    }

                    const index = cache.department.findIndex(d => d.id === id);
                    if (index === -1) {
                        ctx.status = 404;
                        ctx.body = { error: '部门不存在' };
                        return;
                    }
                    const updated = { ...cache.department[index], ...ctx.request.body };
                    cache.department.splice(index, 1, updated);
                    await writeFileAndUpdateCache({
                        ...ctx.state.jsonData,
                        department: cache.department
                    });
                    ctx.status = 200;
                    ctx.body = { message: '部门更新成功', data: updated };
                });
                break;

            case 'DELETE':
                await authMiddleware(ctx, async () => { // 需要权限
                    if (!id) {
                        ctx.status = 400;
                        ctx.body = { error: '缺少部门ID' };
                        return;
                    }

                    const index = cache.department.findIndex(d => d.id === id);
                    if (index === -1) {
                        ctx.status = 404;
                        ctx.body = { error: '部门不存在' };
                        return;
                    }

                    cache.department.splice(index, 1);
                    await writeFileAndUpdateCache({
                        ...ctx.state.jsonData,
                        department: cache.department
                    });

                    ctx.status = 200;
                    ctx.body = { message: '部门删除成功' };
                });
                break;

            default:
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
        }
        return;
    }

    // ====================== 用户接口 ======================
    if (ctx.path.startsWith('/user')) {
        const id = ctx.path.split('/')[2];
        switch (ctx.method) {
            case 'GET': {
                // 使用块级作用域
                let username = '', phone = '', employees = '', data = '', department = '';
                ({ username, phone, employees, data, department } = ctx.query);
                let result = [...cache.user];

                // 优化: 链式过滤，减少循环次数
                if (username) result = result.filter(u => u.username.includes(username));
                if (phone) result = result.filter(u => u.phone.includes(phone));
                if (employees) result = result.filter(u => u.employees.includes(employees));
                if (data) result = result.filter(u => u.data === data);
                if (department) result = result.filter(u => u.department.includes(department));

                ctx.body = result;
                break;
            }

            case 'POST':
                // 确保所有需要的变量都在当前作用域中被声明
                const { phone, password } = ctx.request.body;
                // console.log(phone,password,username)
                // console.log('从请求体中获取的username:', username);
                if (phone && password) {
                    if (cache.user.length === 0) {
                        ctx.status = 500;
                        ctx.body = { error: '缓存中无用户数据' };
                        return;
                    }
                    // 登录/注册逻辑
                    const existing = cache.user.find(u => {
                        console.log(u);
                        const phoneInCache = u.phone + '';
                        const inputPhone = phone + '';
                        const passwordInCache = u.password + '';
                        const inputPassword = password + '';
                        return phoneInCache === inputPhone && passwordInCache === inputPassword;
                    });
                    if (existing) {
                        const token = generateToken(existing);
                        existing.token = token;
                        ctx.status = 200;
                        // const userUsername = existing.username || '未知用户'; 
                        ctx.body = {
                            // username: userUsername,
                            message: '登录成功',
                            data: existing,
                        };
                        console.log('登录响应数据:', ctx.body);
                    } else {
                        const { department = '员工' } = ctx.request.body;
                        const newId = `ZT${(cache.user.length + 1).toString().padStart(6, '0')}`;
                        const newUser = {
                            // username:username || phone,  // 使用解构赋值中获取的username
                            phone,
                            password,
                            department,
                            id: newId,
                            data: new Date().toISOString().split('T')[0],
                            employees: '在职',
                            employeestype: "临时工",
                            createTime: new Date().toISOString()
                        };
                        cache.user.push(newUser);
                        await writeFileAndUpdateCache({
                            ...ctx.state.jsonData,
                            user: cache.user
                        });
                        const token = generateToken(newUser);
                        newUser.token = token;
                        ctx.status = 201;
                        ctx.body = {
                            message: '注册成功并自动登录',
                            data: newUser,
                        };
                    }
                } else {
                    await authMiddleware(ctx, async () => { // 需要权限
                        const newUser = ctx.request.body;
                        const required = ['username', 'department'];
                        const missing = required.filter(f => !newUser[f]);

                        if (missing.length > 0) {
                            ctx.status = 400;
                            ctx.body = { error: `缺少必填字段：${missing.join(', ')}` };
                            return;
                        }

                        const lastId = cache.user.length > 0
                            ? cache.user[cache.user.length - 1].id
                            : 'ZT000000';
                        const newId = `ZT${(parseInt(lastId.slice(2)) + 1).toString().padStart(6, '0')}`;

                        const user = {
                            ...newUser,
                            id: newId,
                            department: newUser.department || '员工',
                            data: newUser.data || new Date().toISOString().split('T')[0],
                            employees: newUser.employees || '在职',
                            password: newUser.password || '1q2w3e4r5t', // 添加默认密码
                            createTime: new Date().toISOString()
                        };

                        cache.user.push(user);
                        await writeFileAndUpdateCache({
                            ...ctx.state.jsonData,
                            user: cache.user
                        });

                        ctx.status = 201;
                        ctx.body = { message: '用户添加成功', data: user };
                    });
                }
                break;

            case 'DELETE':
                await authMiddleware(ctx, async () => { // 需要权限
                    if (!id) {
                        ctx.status = 400;
                        ctx.body = { error: '缺少用户ID' };
                        return;
                    }

                    const index = cache.user.findIndex(u => u.id === id);
                    if (index === -1) {
                        ctx.status = 404;
                        ctx.body = { error: '用户不存在' };
                        return;
                    }

                    cache.user.splice(index, 1);
                    await writeFileAndUpdateCache({
                        ...ctx.state.jsonData,
                        user: cache.user
                    });

                    ctx.status = 200;
                    ctx.body = { message: '用户删除成功' };
                });
                break;

            default:
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
        }
        return;
    }

    // ====================== 财务接口 ======================
    if (ctx.path.startsWith('/finance')) {
        const id = ctx.path.split('/')[2];
        switch (ctx.method) {
            case 'GET':
                const { date, vehicle, expenseType, department, handler } = ctx.query;
                let result = [...cache.finance];
                if (date) result = result.filter(item => item.date === date);
                if (vehicle) result = result.filter(item => item.vehicle === vehicle);
                if (expenseType) result = result.filter(item => item.expenseType === expenseType);
                if (department) result = result.filter(item => item.department === department);
                if (handler) result = result.filter(item => item.handler === handler);
                ctx.body = result;
                break;
            case 'POST':
                const newFinanceItem = ctx.request.body;
                const requiredFields = [ 'date', 'vehicle', 'expenseType', 'amount', 'department', 'handler'];
                const missing = requiredFields.filter(field => !newFinanceItem[field]);
                if (missing.length > 0) {
                    ctx.status = 400;
                    ctx.body = { error: `缺少必填字段：${missing.join(', ')}` };
                    return;
                }

                // 生成唯一ID (格式: FIN-时间戳-4位随机数)
                const timestamp = Date.now();
                const randomPart = Math.floor(1000 + Math.random() * 9000);
                newFinanceItem.id = `FIN-${timestamp}-${randomPart}`;

                // 设置创建时间
                newFinanceItem.createTime = new Date().toISOString();

                cache.finance.push(newFinanceItem);
                await writeFileAndUpdateCache({ finance: cache.finance });
                ctx.status = 201;
                ctx.body = { message: '财务记录添加成功', data: newFinanceItem };
                break;
            case 'PUT':
                if (!id) {
                    ctx.status = 400;
                    ctx.body = { error: '缺少记录ID' };
                    return;
                }
                const index = cache.finance.findIndex(item => item.id === id);
                if (index === -1) {
                    ctx.status = 404;
                    ctx.body = { error: '记录不存在' };
                    return;
                }
                const updatedItem = { ...cache.finance[index], ...ctx.request.body };
                cache.finance.splice(index, 1, updatedItem);
                await writeFileAndUpdateCache({ finance: cache.finance });
                ctx.status = 200;
                ctx.body = { message: '财务记录更新成功', data: updatedItem };
                break;
            case 'DELETE':
                if (!id) {
                    ctx.status = 400;
                    ctx.body = { error: '缺少记录ID' };
                    return;
                }
                const indexToDelete = cache.finance.findIndex(item => item.id === id);
                if (indexToDelete === -1) {
                    ctx.status = 404;
                    ctx.body = { error: '记录不存在' };
                    return;
                }
                cache.finance.splice(indexToDelete, 1);
                await writeFileAndUpdateCache({ finance: cache.finance });
                ctx.status = 200;
                ctx.body = { message: '财务记录删除成功' };
                break;
            default:
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
        }
        return;
    }

    // ====================== 流程审批接口 ======================
    if (ctx.path.startsWith('/processApproval')) {
        const id = ctx.path.split('/')[2];
        const status = ctx.query.status;
        
        switch (ctx.method) {
            case 'GET':
                const processApprovalData = cache.processApproval || [];
                if (status) {
                    ctx.body = processApprovalData.filter(item => item.status === status);
                } else {
                    ctx.body = processApprovalData;
                }
                break;
            case 'POST':
                const newApproval = ctx.request.body;
                const requiredFields = ['applyDate', 'type', 'applicant','reason'];
                const missing = requiredFields.filter(field =>!newApproval[field]);
                
                if (missing.length > 0) {
                    ctx.status = 400;
                    ctx.body = { error: `缺少必填字段：${missing.join(', ')}` };
                    return;
                }
                newApproval.id = `AP${Date.now()}`;
                newApproval.status = 'pending';
                // 接收前端传递的审批人参数，如果没传则设为空字符串
                newApproval.approver = newApproval.approver || ''; 
                
                cache.processApproval.push(newApproval);
                await writeFileAndUpdateCache({ processApproval: cache.processApproval });
                
                ctx.status = 201;
                ctx.body = { message: '审批申请添加成功', data: newApproval };
                break;
            case 'PUT':
                if (!id) {
                    ctx.status = 400;
                    ctx.body = { error: '缺少审批记录ID' };
                    return;
                }
                const approvalIndex = cache.processApproval.findIndex(item => item.id === id);
                if (approvalIndex === -1) {
                    ctx.status = 404;
                    ctx.body = { error: '审批记录不存在' };
                    return;
                }
                const approvalItem = cache.processApproval[approvalIndex];
                // 接收前端传递的审批结果、审批意见和审批人参数
                const { approvalResult, approvalComment, approver } = ctx.request.body; 
                
                if (!approvalResult) {
                    ctx.status = 400;
                    ctx.body = { error: '缺少审批结果' };
                    return;
                }
                approvalItem.status = approvalResult === 'approved'? 'approved' :'rejected';
                // 如果前端传递了审批人参数，就使用前端传递的值，否则保留原审批人（如果有的话）
                approvalItem.approver = approver || approvalItem.approver; 
                approvalItem.approvalDate = new Date().toISOString();
                approvalItem.approvalComment = approvalComment || '';
                
                cache.processApproval[approvalIndex] = approvalItem;
                await writeFileAndUpdateCache({ processApproval: cache.processApproval });
                
                ctx.body = { 
                    message: approvalResult === 'approved'? '审批同意成功' : '审批拒绝成功', 
                    data: approvalItem 
                };
                break;
            default:
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
        }
        
        return;
    }

    // ====================== 物料管理接口 ======================
    if (ctx.path.startsWith('/materials')) {
        const id = ctx.path.split('/')[2];
        const { name, category, status } = ctx.query;

        switch (ctx.method) {
            case 'GET':
                if (id) {
                    const material = cache.materials.find(m => m.id === id || m.code === id);
                    ctx.body = material || { error: '物料不存在' };
                } else {
                    let filtered = [...cache.materials];
                    if (name) filtered = filtered.filter(m => m.name.includes(name));
                    if (category) filtered = filtered.filter(m => m.category.includes(category));
                    if (status) filtered = filtered.filter(m => m.status === status);
                    ctx.body = filtered;
                }
                break;

            case 'POST':
                const newMaterial = ctx.request.body;

                if (typeof newMaterial.stock === 'number') {
                    newMaterial.stock = newMaterial.stock.toString();
                }

                const requiredFields = ['name', 'code', 'category', 'stock'];
                const missing = requiredFields.filter(f =>
                    newMaterial[f] === undefined ||
                    newMaterial[f] === null ||
                    newMaterial[f] === ''
                );

                if (missing.length > 0) {
                    ctx.status = 400;
                    ctx.body = { error: `缺少必填字段：${missing.join(', ')}` };
                    return;
                }

                const exists = cache.materials.some(m =>
                    String(m.code) === String(newMaterial.code)
                );

                if (exists) {
                    ctx.status = 409;
                    ctx.body = { error: '物料编码已存在' };
                    return;
                }

                newMaterial.id = String(newMaterial.code);
                newMaterial.date = new Date().toISOString().split('T')[0];
                newMaterial.status = newMaterial.status || '正常';

                cache.materials.push(newMaterial);
                await writeFileAndUpdateCache({ materials: cache.materials });

                ctx.status = 201;
                ctx.body = { message: '物料添加成功', data: newMaterial };
                break;

            default:
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
        }
        return;
    }

    // ====================== 车辆管理接口 ======================
    if (ctx.path.startsWith('/vehicleManagement')) {
        switch (ctx.method) {
            case 'GET':
                const { plate, type, brand, driver, status } = ctx.query;

                // 基础查询：返回所有车辆
                let result = [...cache.vehicleManagement];

                // 按车牌号精确查询
                if (plate) {
                    const vehicle = result.find(v => v.plate === plate);
                    ctx.body = vehicle || { error: '车辆不存在' };
                    return;
                }

                // 按其他条件筛选
                if (type) result = result.filter(v => v.type === type);
                if (brand) result = result.filter(v => v.brand.includes(brand));
                if (driver) result = result.filter(v => v.driver.includes(driver));
                if (status) result = result.filter(v => v.status === status);

                ctx.body = result;
                break;

            case 'POST':
                // 移除了requireAuth中间件，不再需要认证
                const newVehicleInfo = ctx.request.body;
                const requiredFields = ['plate', 'type', 'brand', 'driver'];
                const missing = requiredFields.filter(field => !newVehicleInfo[field]);

                if (missing.length > 0) {
                    ctx.status = 400;
                    ctx.body = { error: `缺少必填字段：${missing.join(', ')}` };
                    return;
                }

                // 检查车牌号是否已存在
                const exists = cache.vehicleManagement.some(v => v.plate === newVehicleInfo.plate);
                if (exists) {
                    ctx.status = 409;
                    ctx.body = { error: '车牌号已存在' };
                    return;
                }

                // 添加默认字段
                newVehicleInfo.lastUse = new Date().toISOString().split('T')[0];
                newVehicleInfo.status = newVehicleInfo.status || '正常';
                newVehicleInfo.createTime = new Date().toISOString();

                cache.vehicleManagement.push(newVehicleInfo);
                await writeFileAndUpdateCache({ vehicleManagement: cache.vehicleManagement });

                ctx.status = 201;
                ctx.body = { message: '车辆信息添加成功', data: newVehicleInfo };
                break;

            default:
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
        }
        return;
    }

    // ====================== 岗位管理接口 ======================
    if (ctx.path.startsWith('/jobManagement')) {
        console.log('[岗位管理] 当前缓存状态:', {
            jobManagementCount: cache.jobManagement.length,
            lastFileUpdate: new Date(lastFileUpdate).toISOString()
        });

        switch (ctx.method) {
            case 'GET':
                // 查询岗位信息
                {
                    const id = ctx.path.split('/')[2];
                    const { jobName, jobCode, jobType, orgName } = ctx.query;

                    let result = [...cache.jobManagement];

                    // 按ID精确查询
                    if (id) {
                        const job = result.find(job => job.id === id);
                        ctx.body = job || { error: '岗位不存在' };
                        return;
                    }

                    // 按条件筛选查询
                    if (jobName) result = result.filter(job => job.jobName.includes(jobName));
                    if (jobCode) result = result.filter(job => job.jobCode.includes(jobCode));
                    if (jobType) result = result.filter(job => job.jobType.includes(jobType));
                    if (orgName) result = result.filter(job => job.orgName.includes(orgName));

                    ctx.body = result;
                    console.log('[岗位管理] 查询成功 - 返回数据数量:', result.length);
                }
                break;

            case 'POST':
                // 添加岗位信息
                {
                    const newJobInfo = ctx.request.body;
                    const requiredFields = ['jobName', 'employeeCount', 'jobType'];
                    const missing = requiredFields.filter(field => !newJobInfo[field]);

                    if (missing.length > 0) {
                        ctx.status = 400;
                        ctx.body = { error: `缺少必填字段：${missing.join(', ')}` };
                        return;
                    }
                    newJobInfo.orgName = newJobInfo.orgName || '北京xxx技术有限公司';
                    newJobInfo.jobCode = newJobInfo.jobCode || 'A1B2C3';
                    newJobInfo.description=newJobInfo.description||'岗位描述信息';
                    // 生成唯一ID
                    newJobInfo.id = `JOB-${Date.now()}-${Math.floor(Math.random() * 1000)}`;

                    // 添加创建时间
                    newJobInfo.createTime = new Date().toISOString();

                    // 记录添加前的状态
                    const beforeAddCount = cache.jobManagement.length;

                    // 添加新岗位
                    cache.jobManagement.push(newJobInfo);

                    try {
                        await writeFileAndUpdateCache({ jobManagement: cache.jobManagement });
                        console.log('[岗位管理] 新增成功 - 岗位ID:', newJobInfo.id);

                        ctx.status = 201;
                        ctx.body = {
                            message: '岗位信息添加成功',
                            data: newJobInfo
                        };
                    } catch (error) {
                        // 添加失败，回滚缓存
                        cache.jobManagement = cache.jobManagement.slice(0, beforeAddCount);
                        console.error('[岗位管理] 新增失败:', error);

                        ctx.status = 500;
                        ctx.body = {
                            error: '保存岗位信息失败',
                            detail: error.message
                        };
                    }
                }
                break;

            case 'PUT':
                // 更新岗位信息
                {
                    const id = ctx.path.split('/')[2];
                    const updateJobInfo = ctx.request.body;

                    const jobIndex = cache.jobManagement.findIndex(job => job.id === id);
                    if (jobIndex === -1) {
                        ctx.status = 404;
                        ctx.body = { error: '岗位不存在' };
                        return;
                    }

                    const originalJob = cache.jobManagement[jobIndex];
                    cache.jobManagement[jobIndex] = {
                        ...originalJob,
                        ...updateJobInfo,
                        updateTime: new Date().toISOString()
                    };

                    try {
                        await writeFileAndUpdateCache({ jobManagement: cache.jobManagement });
                        console.log('[岗位管理] 更新成功 - 岗位ID:', id);

                        ctx.status = 200;
                        ctx.body = {
                            message: '岗位信息更新成功',
                            data: cache.jobManagement[jobIndex]
                        };
                    } catch (error) {
                        // 更新失败，回滚缓存
                        cache.jobManagement[jobIndex] = originalJob;
                        console.error('[岗位管理] 更新失败:', error);

                        ctx.status = 500;
                        ctx.body = {
                            error: '更新岗位信息失败',
                            detail: error.message
                        };
                    }
                }
                break;

            case 'DELETE':
                // 删除岗位信息
                {
                    const id = ctx.path.split('/')[2];

                    const jobIndex = cache.jobManagement.findIndex(job => job.id === id);
                    if (jobIndex === -1) {
                        ctx.status = 404;
                        ctx.body = { error: '岗位不存在' };
                        return;
                    }

                    const deletedJob = cache.jobManagement[jobIndex];

                    // 从缓存中删除
                    cache.jobManagement.splice(jobIndex, 1);

                    try {
                        await writeFileAndUpdateCache({ jobManagement: cache.jobManagement });
                        console.log('[岗位管理] 删除成功 - 岗位ID:', id);

                        ctx.status = 200;
                        ctx.body = {
                            message: '岗位信息删除成功',
                            deleted: deletedJob
                        };
                    } catch (error) {
                        // 删除失败，回滚缓存
                        cache.jobManagement.splice(jobIndex, 0, deletedJob);
                        console.error('[岗位管理] 删除失败:', error);

                        ctx.status = 500;
                        ctx.body = {
                            error: '删除岗位信息失败',
                            detail: error.message
                        };
                    }
                }
                break;

            default:
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
        }
        return;
    }

    // ====================== 会议管理接口 ======================
    if (ctx.path.startsWith('/meeting')) {
        const id = ctx.path.split('/')[2];
        const { name, room, type, status, startDate, endDate } = ctx.query;

        switch (ctx.method) {
            case 'GET':
                console.log('[会议管理] 查询会议列表');

                if (id) {
                    // 根据ID查询单个会议
                    const meeting = cache.meeting.find(m => m.id === id);
                    ctx.body = meeting || { error: '会议不存在' };
                } else {
                    // 根据条件筛选会议
                    let filteredMeetings = [...cache.meeting];

                    if (name) filteredMeetings = filteredMeetings.filter(m => m.name.includes(name));
                    if (room) filteredMeetings = filteredMeetings.filter(m => m.room === room);
                    if (type) filteredMeetings = filteredMeetings.filter(m => m.type === type);
                    if (status) filteredMeetings = filteredMeetings.filter(m => m.status === status);

                    // 日期范围查询
                    if (startDate || endDate) {
                        filteredMeetings = filteredMeetings.filter(m => {
                            const meetingDate = new Date(m.date);
                            const start = startDate ? new Date(startDate) : new Date(0);
                            const end = endDate ? new Date(endDate) : new Date();

                            return meetingDate >= start && meetingDate <= end;
                        });
                    }

                    ctx.body = filteredMeetings;
                }
                break;

            case 'POST':
                console.log('[会议管理] 创建会议'); // 移除权限验证中间件
    
                const newMeeting = ctx.request.body;
                const requiredFields = ['name', 'room', 'type', 'date'];
                const missing = requiredFields.filter(field => !newMeeting[field]);
            
                if (missing.length > 0) {
                    ctx.status = 400;
                    ctx.body = { error: `缺少必填字段：${missing.join(', ')}` };
                    return;
                }
            
                // 生成唯一ID
                newMeeting.id = `MEET-${Date.now()}`;
            
                // 设置默认值
                newMeeting.status = newMeeting.status || '未开始';
                newMeeting.attendees = newMeeting.attendees || '0 人';
                newMeeting.createTime = new Date().toISOString();
            
                // 添加到缓存
                cache.meeting.push(newMeeting);
            
                // 持久化到文件
                await writeFileAndUpdateCache({ meeting: cache.meeting });
            
                ctx.status = 201;
                ctx.body = {
                    message: '会议创建成功',
                    data: newMeeting
                };
                break;

            default:
                ctx.status = 405; // 方法不允许
                ctx.body = { error: '该接口仅支持GET和POST方法' };
        }
        return;
    }
    ctx.status = 404;
    ctx.body = { error: '接口不存在' };
});


// 启动服务
readFileAndUpdateCache().then(() => {
    app.listen(3000, '172.20.10.10', () => {
        console.log('服务器启动，端口 3000');
        console.log('接口列表：');
        console.log('GET    /user        - 查询用户');
        console.log('POST   /user        - 添加用户 / 登录注册判断');
        console.log('DELETE /user/:id    - 删除用户');
        console.log('GET    /department  - 查询部门');
        console.log('POST   /department  - 添加部门');
        console.log('PUT    /department/:id  - 编辑部门');
        console.log('DELETE /department/:id  - 删除部门');
        console.log('GET    /finance     - 财务接口');
        console.log('GET    /processApproval  - 流程审批');
        console.log('GET    /materials    - 查询物料');
        console.log('POST   /materials    - 添加物料');
        console.log('GET    /vehicleManagement - 查询车辆');
        console.log('POST   /vehicleManagement - 添加车辆');
        console.log('GET    /jobManagement - 查询岗位');
        console.log('POST   /jobManagement - 添加岗位');
        console.log('受保护的接口：');
        console.log('POST   /user        - 添加用户（需要Token）');
        console.log('DELETE /user/:id    - 删除用户（需要Token）');
        console.log('POST   /department  - 添加部门（需要Token）');
        console.log('PUT    /department/:id  - 编辑部门（需要Token）');
        console.log('DELETE /department/:id  - 删除部门（需要Token）');
    });
});